<?php

if( !defined('IN_ELCIUS') ) exit;

$raiders = KiwiDB::Get('raiders');

// editor/admin stuff
if( KiwiAuth::IsEditor() == true ){
	// edit order of raider list
	
	$name = GetRequestVar('Move');
	if( isset($name) ){
		// move raider up/down
		$dir = ( GetRequestVar('Dir') == 'Up' ? -1 : 1 );
		foreach( $raiders as $i => $raider ){
			if( $raider['Name'] == $name ){
				$raider['Position'] = max($raider['Position']+$dir,0);
				if( KiwiDB::Set('raiders',$raider) ){
					$raiders[ $i ] = $raider;
				}
			}
		}
	}
	
	$name = GetRequestVar('Delete');
	if( isset($name) ){
		// delete raider
		foreach( $raiders as $i => $raider ){
			if( $raider['Name'] == $name ){
				if( KiwiDB::Delete('raiders',$raider) ){
					unset( $raiders[ $i ] );
				}
			}
		}
	}
	
	// insert/change raider
	if( GetRequestVar('AddRaider') ){
		$raider = array(
			'Name' => GetRequestVar('RaiderName'),
			'Comment' => GetRequestVar('Comment'),
			'Characters' => trim( preg_replace( "/[^\p{L},]+/u", '', GetRequestVar('Characters') ), ',' ),
			'Position' => 0,
		);
		// data will be cleaned by KiwiDB
		if( KiwiDB::Set( 'raiders', $raider ) ){
			// database updated
			// delate any old data from array
			foreach( $raiders as $i => $r ){
				if( $r['Name'] == $raider['Name'] ){
					unset($raiders[$i]);
				}
			}
			// insert new stuff
			$raiders[] = $raider;
		}
	}
}

usort( $raiders, function($a,$b){ return $a['Position'] > $b['Position']; } );

foreach( $raiders as $i => $raider ){
	
	$raider['Name'] = array(
		'URL' => urlencode( $raider['Name'] ),
		'Safe' => htmlspecialchars( $raider['Name'] ),
		'Raw' => $raider['Name'],
	);
	
	$raider['Characters'] = explode(',', $raider['Characters'] );
	
	foreach( $raider['Characters'] as $j => $name ){
		
		// TODO: clean up, review, validate & clean charData before use, etc.
		// check for empty data (api offline or timed out)
		if( empty( $name ) ){
			unset( $raider['Characters'][$j] );
			continue;
		}
		
		$charData = WowArmory::Fetch('character',$name,'frostmourne','talents,items,titles,professions,progression');
		
		if( $charData ){
			
			$classInfo = array( 1 => 
				array("id" => 1, "mask" => 1, "powerType" => "rage", "name" => "Warrior"),
				array("id" => 2, "mask" => 2, "powerType" => "mana", "name" => "Paladin"),
				array("id" => 3, "mask" => 4, "powerType" => "focus", "name" => "Hunter"),
				array("id" => 4, "mask" => 8, "powerType" => "energy", "name" => "Rogue"),
				array("id" => 5, "mask" => 16, "powerType" => "mana", "name" => "Priest"),
				array("id" => 6, "mask" => 32, "powerType" => "runic-power", "name" => "Death Knight"),
				array("id" => 7, "mask" => 64, "powerType" => "mana", "name" => "Shaman"),
				array("id" => 8, "mask" => 128, "powerType" => "mana", "name" => "Mage"),
				array("id" => 9, "mask" => 256, "powerType" => "mana", "name" => "Warlock"),
				array("id" => 10, "mask" => 512, "powerType" => "energy", "name" => "Monk"),
				array("id" => 11, "mask" => 1024, "powerType" => "mana", "name" => "Druid"),
			);
			
			$raider['Characters'][$j] = array(
				'Name' => $name,
				'ClassName' => $classInfo[$charData['class']]['name'],
				'Class' => $charData['class'],
				'Race' => $charData['race'],
				'Gender' => $charData['gender'],
				'Level' => $charData['level'],
				'Thumbnail' => $charData['thumbnail'],
				'Spec1Name' => 'N/A',
				'Spec1Selected' => '',
				'Spec2Name' => 'N/A',
				'Spec2Selected' => '',
				'Spec1Icon' => 'inv_misc_questionmark',
				'Spec2Icon' => 'inv_misc_questionmark',
				'ItemLevel' => $charData['items']['averageItemLevel'],
				'ItemLevelEquipped' => $charData['items']['averageItemLevelEquipped'],
				'Progression' => '0/17',
				'ProgressionDifficulty' => 'Normal',
				'ProgressionDifficultyShort' => 'N',
			);
			
			// specs
			if( isset( $charData['talents'][0]['spec'] ) ){
				$raider['Characters'][$j]['Spec1Name'] = $charData['talents'][0]['spec']['name'];
				if( isset(  $charData['talents'][0]['selected'] ) and $charData['talents'][0]['selected'] == 1 ) $raider['Characters'][$j]['Spec1Selected'] = 'Active';
				else $raider['Characters'][$j]['Spec2Selected'] = 'Active';
				$raider['Characters'][$j]['Spec1Icon'] = $charData['talents'][0]['spec']['icon'];
			}
			if( isset( $charData['talents'][1]['spec'] ) ){
				$raider['Characters'][$j]['Spec2Name'] = $charData['talents'][1]['spec']['name'];
				$raider['Characters'][$j]['Spec2Icon'] = $charData['talents'][1]['spec']['icon'];
			}
			
			// progression
			$raider['Characters'][$j]['BossKills'] = array();
			$killsNormal = 0;
			$killsHeroic = 0;
			$numBosses = 0;
			foreach( $charData['progression']['raids'] as $raidId => $raidInfo ) {
				// 27 = Mogu'shan Vaults, 28 = Heart of Fear, 29 = Terrace of Endless Spring
				// TODO: Garalon bug fix
				if(  $raidId >= 27 && $raidId <= 29 ) {
					foreach( $raidInfo['bosses'] as $k => $bossData ) {
						if( $k < 6 ){
							$numBosses++;
							if( $bossData['heroicKills'] != 0 ) $killsHeroic++;
							elseif( $bossData['normalKills'] != 0 ) $killsNormal++;
							$raider['Characters'][$j]['BossKills'][] = array(
								'BossName' => $bossData['name'],
								'BossKillStatus' => ( ( $bossData['heroicKills'] > 0 ) ? 'Heroic' : ( ( $bossData['normalKills'] > 0 ) ? 'Normal' : 'None' ) ),
								'BossHeroicKills' => $bossData['heroicKills'],
								'BossNormalKills' => $bossData['normalKills'],
								'BossID' => $bossData['id']
							);
						}
					}
				}
			}
			if( $killsHeroic > 0 ){
				$raider['Characters'][$j]['Progression'] = $killsHeroic.'/'.$numBosses;
				$raider['Characters'][$j]['ProgressionDifficulty'] = 'Heroic';
				$raider['Characters'][$j]['ProgressionDifficultyShort'] = 'H';
			}
			else{
				$raider['Characters'][$j]['Progression'] = $killsNormal.'/'.$numBosses;
			}
			
			// professions
			if( isset( $charData['professions']['primary'] ) ) {
				foreach( $charData['professions']['primary'] as $k => $prof ) {
					$raider['Characters'][$j]['Prof'.($k+1).'Name'] = $prof['name'];
					$raider['Characters'][$j]['Prof'.($k+1).'Rank'] = $prof['rank'];
					$raider['Characters'][$j]['Prof'.($k+1).'IconURL'] = 'http://us.media.blizzard.com/wow/icons/18/'.$prof['icon'].'.jpg';
				}
			}
		}
	}
	
	$raiders[$i] = $raider;
}

$PageData['Raiders'] = &$raiders;

?>